package jdx_14_基于CAS的新锁;

import java.util.concurrent.CountDownLatch;

public class T06_TestCountDownLatch {
    public static void main(String[] args) {
//        usingJoin();
        usingCountDownLatch();
    }

    private static void usingCountDownLatch() {
        Thread[] threads = new Thread[100];
        //CountDownLatch 叫做"倒数门闩" (数到之后就把门打开了的意思)
        CountDownLatch latch = new CountDownLatch(threads.length);//门闩的上面记了个数:100

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 10000; j++) result += j;
                latch.countDown(); //每条线程结束的时候 倒数一次,这是个原子操作(latch底层实现了锁，保证了线程安全)
            });
        }

        //开启所有的线程
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        //插住门闩
        try {
            latch.await(); //门闩在这里把门锁住，只有等到 倒数为0 的时候，门才能打开，继续向下执行(类似于阻塞,所以不需要关注什么性能)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //门闩的作用：就是等待多少个线程结束，我来做...
        System.out.println("end latch");
    }

    private static void usingJoin() {
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 10000; j++) result += j;
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join();
                //如果使用的是 join 则不好控制线程数,对于"countDown()"我可以好几条线程才执行一次，也可以一条线程执行好几次的countDown()
                //使用门闩会比较灵活
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("end join");
    }
}
